package com.blue.spring.convertor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import com.blue.core.dict.annotation.DictParser;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class StringToEnumConverterFactory implements ConverterFactory<String, Enum<?>>
{
	private static DictParser dictParser = DictParser.getInstance();
	
	@Override
	public <T extends Enum<?>> Converter<String, T> getConverter(Class<T> targetType)
	{
		if (!targetType.isEnum())
			throw new IllegalArgumentException("目标类型不是 enum：" + targetType.getName());
		
		return new StringToEnum(targetType);
	}


	private class StringToEnum<T extends Enum<T>> implements Converter<String, T>
	{
		private final Class<T> enumType;

		public StringToEnum(Class<T> enumType)
		{
			this.enumType = enumType;
		}

		@Override
		public T convert(String source)
		{
			if (source == null || source.isEmpty())
				return null;
			
			if (StringUtils.isNumeric(source))
			{
				Integer index = Integer.valueOf(source.trim());
				return dictParser.getFromIndex(enumType, index);
			}
			else
			{
				return (T) Enum.valueOf(this.enumType, source.trim());
			}
		}
	}
}
